<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简化阅读器 - 《缙青年》电子期刊</title>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
            background: #f5f5f5;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header {
            background: #2c3e50;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            margin: 0;
            font-size: 18px;
        }
        .controls {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            text-align: center;
        }
        .controls button {
            background: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            margin: 0 5px;
            border-radius: 4px;
            cursor: pointer;
        }
        .controls button:hover {
            background: #2980b9;
        }
        .controls button:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
        }
        .viewer {
            padding: 20px;
            text-align: center;
            min-height: 500px;
        }
        .loading {
            color: #7f8c8d;
            font-size: 18px;
            margin: 50px 0;
        }
        .error {
            color: #e74c3c;
            background: #fdf2f2;
            padding: 20px;
            border-radius: 5px;
            margin: 20px;
        }
        #pdfCanvas {
            border: 1px solid #ddd;
            max-width: 100%;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .page-info {
            margin: 15px 0;
            font-size: 16px;
            color: #2c3e50;
        }
        .back-btn {
            background: #95a5a6;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
        .back-btn:hover {
            background: #7f8c8d;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <a href="index.html" class="back-btn">← 返回主页</a>
            <h1 id="bookTitle">《缙青年》第三期</h1>
            <div></div>
        </div>
        
        <div class="controls">
            <button onclick="loadPDF()" id="loadBtn">加载PDF</button>
            <button onclick="prevPage()" id="prevBtn" disabled>上一页</button>
            <button onclick="nextPage()" id="nextBtn" disabled>下一页</button>
            <input type="number" id="pageInput" min="1" placeholder="页码" style="width: 60px; padding: 5px; margin: 0 10px;">
            <button onclick="goToPage()" id="goBtn" disabled>跳转</button>
        </div>
        
        <div class="viewer">
            <div id="status" class="loading">点击"加载PDF"开始阅读</div>
            <div class="page-info" id="pageInfo" style="display: none;"></div>
            <canvas id="pdfCanvas" style="display: none;"></canvas>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
    <script>
        // 配置PDF.js
        if (typeof pdfjsLib !== 'undefined') {
            pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
        }

        let pdfDoc = null;
        let currentPage = 1;
        let totalPages = 0;
        const canvas = document.getElementById('pdfCanvas');
        const ctx = canvas.getContext('2d');

        function updateStatus(message, isError = false) {
            const statusEl = document.getElementById('status');
            statusEl.textContent = message;
            statusEl.className = isError ? 'error' : 'loading';
        }

        function updatePageInfo() {
            const pageInfoEl = document.getElementById('pageInfo');
            if (pdfDoc) {
                pageInfoEl.textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;
                pageInfoEl.style.display = 'block';
                
                // 更新页码输入框
                document.getElementById('pageInput').value = currentPage;
                document.getElementById('pageInput').max = totalPages;
            }
        }

        function updateButtons() {
            document.getElementById('prevBtn').disabled = !pdfDoc || currentPage <= 1;
            document.getElementById('nextBtn').disabled = !pdfDoc || currentPage >= totalPages;
            document.getElementById('goBtn').disabled = !pdfDoc;
            document.getElementById('pageInput').disabled = !pdfDoc;
        }

        async function loadPDF() {
            try {
                updateStatus('正在加载PDF...');
                console.log('开始加载PDF');

                if (typeof pdfjsLib === 'undefined') {
                    throw new Error('PDF.js库未加载');
                }

                const pdfPath = 'pdfs/《缙青年》第三期.pdf';
                console.log('PDF路径:', pdfPath);

                const loadingTask = pdfjsLib.getDocument(pdfPath);
                
                loadingTask.onProgress = (progress) => {
                    if (progress.total > 0) {
                        const percent = Math.round((progress.loaded / progress.total) * 100);
                        updateStatus(`正在加载PDF... ${percent}%`);
                    }
                };

                pdfDoc = await loadingTask.promise;
                totalPages = pdfDoc.numPages;
                
                console.log(`PDF加载成功，共 ${totalPages} 页`);
                updateStatus('PDF加载成功！');
                
                currentPage = 1;
                await renderPage();
                updatePageInfo();
                updateButtons();

                // 隐藏加载按钮
                document.getElementById('loadBtn').style.display = 'none';

            } catch (error) {
                console.error('PDF加载失败:', error);
                updateStatus(`PDF加载失败: ${error.message}`, true);
            }
        }

        async function renderPage() {
            if (!pdfDoc) return;

            try {
                updateStatus('正在渲染页面...');
                console.log(`渲染第 ${currentPage} 页`);

                const page = await pdfDoc.getPage(currentPage);
                const viewport = page.getViewport({ scale: 1.2 });

                canvas.width = viewport.width;
                canvas.height = viewport.height;

                const renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                };

                await page.render(renderContext).promise;

                canvas.style.display = 'block';
                updateStatus('');
                updatePageInfo();
                updateButtons();

                console.log(`第 ${currentPage} 页渲染完成`);

            } catch (error) {
                console.error('页面渲染失败:', error);
                updateStatus(`页面渲染失败: ${error.message}`, true);
            }
        }

        async function prevPage() {
            if (pdfDoc && currentPage > 1) {
                currentPage--;
                await renderPage();
            }
        }

        async function nextPage() {
            if (pdfDoc && currentPage < totalPages) {
                currentPage++;
                await renderPage();
            }
        }

        async function goToPage() {
            const pageInput = document.getElementById('pageInput');
            const targetPage = parseInt(pageInput.value);
            
            if (pdfDoc && targetPage >= 1 && targetPage <= totalPages) {
                currentPage = targetPage;
                await renderPage();
            } else {
                alert(`请输入1到${totalPages}之间的页码`);
                pageInput.value = currentPage;
            }
        }

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (!pdfDoc) return;
            
            switch (e.key) {
                case 'ArrowLeft':
                case 'ArrowUp':
                    e.preventDefault();
                    prevPage();
                    break;
                case 'ArrowRight':
                case 'ArrowDown':
                case ' ':
                    e.preventDefault();
                    nextPage();
                    break;
                case 'Home':
                    e.preventDefault();
                    currentPage = 1;
                    renderPage();
                    break;
                case 'End':
                    e.preventDefault();
                    currentPage = totalPages;
                    renderPage();
                    break;
            }
        });

        // 页面输入框回车事件
        document.getElementById('pageInput').addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                goToPage();
            }
        });

        // 自动加载（如果有URL参数）
        window.addEventListener('load', () => {
            console.log('简化阅读器页面加载完成');
            
            // 检查URL参数
            const urlParams = new URLSearchParams(window.location.search);
            const bookId = urlParams.get('book');
            
            if (bookId) {
                console.log('检测到书籍参数，自动加载PDF');
                setTimeout(loadPDF, 500);
            }
        });
    </script>
</body>
</html>
